package com.thiswhyme.demo.msgpush.core.impl.nio;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;


/**
 * @description: channel连接状态处理器
 * @author: thiswhyme
 * @date: 2021/9/29
 */
@Slf4j
@ChannelHandler.Sharable
public class NioWsHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        JSONObject jsonObject = JSONUtil.parseObj(msg.text());
        String token = jsonObject.getStr("token");

        // 将token作为自定义属性加入到channel中备用并关联channel
        ctx.channel().attr(AttributeKey.valueOf("token")).setIfAbsent(token);
        ChannelManager.put(token, ctx.channel());

        // 回复消息
        //ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器连接成功"));
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // TODO
        ChannelManager.removeAndClose(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // TODO
        ChannelManager.removeAndClose(ctx.channel());
        ctx.close();
    }
}
